﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DotNetNuke.Services.FileSystem;
namespace SPA_Gallery.Components
{
    public class GalleryDNNFileController : IGalleryController
    {
        public const string configFileName = "config.json";
        public override List<GalleryEntity> GetGalleries(string parentFolder)
        {
            DotNetNuke.Services.FileSystem.FolderInfo parentFolderEntity;
            parentFolderEntity = getRootFolder(parentFolder);

            IEnumerable<IFolderInfo> lstSubGalleries = FolderManager.Instance.GetFolders(parentFolderEntity);

            List<GalleryEntity> toReturn = (from myGallery in lstSubGalleries
                                            select new GalleryEntity() { GalleryId = myGallery.FolderID.ToString(), GalleryName = myGallery.FolderName, ParentId = parentFolder, ThumbUrl = getThumbGallery(myGallery.FolderID) }).ToList();

            return toReturn;
        }
        public override GalleryEntity GetGallery(string currentFolder)
        {
            DotNetNuke.Services.FileSystem.FolderInfo currentFolderEntity;
            currentFolderEntity = getRootFolder(currentFolder);

            string parentId = string.Empty;
            GalleryEntity toReturn;
            if (!string.IsNullOrEmpty(currentFolder))
            {
                string parentFolderPath = currentFolderEntity.FolderPath.TrimEnd('/');
                if (parentFolderPath.Contains('/'))
                {
                    parentFolderPath = parentFolderPath.Substring(0, parentFolderPath.LastIndexOf('/'));
                    if (!string.IsNullOrEmpty(parentFolderPath))
                    {
                        FolderInfo parentFolderEntity = (FolderInfo)FolderManager.Instance.GetFolder(currentFolderEntity.PortalID, parentFolderPath);
                        if (parentFolderEntity != null)
                            parentId = parentFolderEntity.FolderID.ToString();

                    }
                }
                toReturn = new GalleryEntity() { GalleryId = currentFolder, GalleryName = currentFolderEntity.FolderName, ParentId = parentId, ThumbUrl = getThumbGallery(int.Parse(currentFolder)) };
            }
            else
            { toReturn = new GalleryEntity() { GalleryName = "Root" }; }

            return toReturn;

        }
        private string getThumbGallery(int folderId)
        {
            string toReturn = string.Empty;
            FolderInfo currentFolder = getRootFolder(folderId.ToString());
            IEnumerable<IFileInfo> lstFiles = FolderManager.Instance.GetFiles(currentFolder);
            IEnumerable<IFileInfo> lstFilteredFiles = new List<IFileInfo>();
            try
            {
                lstFilteredFiles = (from myFile in lstFiles
                                    where myFile.FileName.StartsWith(Constants.prefixThumb.Substring(0, Constants.prefixThumb.Length - 3))
                                    select myFile);
                if (lstFilteredFiles.Count() > 0)
                {
                    IFileInfo myCurrentFile = lstFilteredFiles.First();
                    toReturn = string.Format("/portals/{0}/{1}", myCurrentFile.PortalId, myCurrentFile.RelativePath);
                }
            }
            catch (Exception)
            {

                throw new Exception(string.Format("Error : foldId - {0} , lstFilteredFiles.count {1}", currentFolder.FolderID, lstFilteredFiles.Count()));
            }
            return toReturn;

        }

        private FolderInfo getRootFolder(string parentFolder)
        {
            DotNetNuke.Services.FileSystem.FolderInfo parentFolderEntity;
            if (!string.IsNullOrEmpty(parentFolder))
            {
                parentFolderEntity = (FolderInfo)FolderManager.Instance.GetFolder(int.Parse(parentFolder));
            }
            else
            {
                parentFolderEntity = (FolderInfo)DotNetNuke.Services.FileSystem.FolderManager.Instance.GetFolder(this.PortalId, string.Format(Components.Constants.RootFolderPathScheme, this.ModuleId));
            }
            return parentFolderEntity;
        }

        public override List<ImageEntity> GetImages(string folderId)
        {
            DotNetNuke.Services.FileSystem.FolderInfo parentFolderEntity;
            parentFolderEntity = getRootFolder(folderId);
            //get config files
           
            IEnumerable<IFileInfo> lstFiles;
            try
            {
                lstFiles = FolderManager.Instance.GetFiles(parentFolderEntity);
            }
            catch (Exception)
            {

                throw new Exception(string.Format("Error FolderId : {0}", parentFolderEntity.FolderID));
            }
            string[] allowedExtensions = new string[] { "jpeg","jpg","png" };
            List<ImageEntity> toReturn = (from myFile in lstFiles
                                          where !myFile.FileName.StartsWith(Constants.prefixThumb.Substring(0, Constants.prefixThumb.Length - 3)) 
                                          && allowedExtensions.Contains(myFile.Extension) 
                                          select new ImageEntity()
                                          {
                                              FileName = myFile.FileName,
                                              GalleryId = folderId,
                                              ImageId = myFile.FileId.ToString(),
                                              FullUrl = string.Format("/portals/{0}/{1}", myFile.PortalId, myFile.RelativePath),
                                              ThumbUrl = string.Format("/portals/{0}/{1}", myFile.PortalId, myFile.RelativePath).Replace(myFile.FileName, string.Format(Constants.prefixThumb, myFile.FileName))
                                          }
                                         ).ToList();
            FileInfo configFile = (FileInfo)FileManager.Instance.GetFile(parentFolderEntity,configFileName);
            System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            if (configFile == null)
            {
                //create empty config file
                
              
              // convert string to stream
              byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(jsSerializer.Serialize(toReturn));
              //byte[] byteArray = Encoding.ASCII.GetBytes(contents);
              System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

              FileManager.Instance.AddFile(parentFolderEntity, configFileName, stream); 
            }
            else { 
            //merge config file with actual files
                System.IO.StreamReader reader = new System.IO.StreamReader(FileManager.Instance.GetFileContent(configFile));
               string jsonConfigContent= reader.ReadToEnd();
             List<ImageEntity> filesExtended= jsSerializer.Deserialize<List<ImageEntity>>(jsonConfigContent);
                List<ImageEntity> finalMerge=(from myFile in toReturn
                                             join myFileExtended in filesExtended 
                                             on myFile.ImageId equals  myFileExtended.ImageId into ps
                                             from myMergeFile in ps.DefaultIfEmpty()
                                             select myMergeFile).ToList();
                toReturn = finalMerge;
                
            }
            return toReturn;

        }

        public override int AddGallery(string parentGalleryId, string galleryName)
        {
            int toReturn = -1;


            //DotNetNuke.Services.FileSystem.FolderManager fc = new FolderManager();
            DotNetNuke.Services.FileSystem.FolderInfo parentFolder = getRootFolder(parentGalleryId);


            DotNetNuke.Services.FileSystem.FolderInfo newFolder = (FolderInfo)FolderManager.Instance.AddFolder(this.PortalId, string.Format("{0}/{1}", parentFolder.FolderPath.TrimEnd("/".ToCharArray()), galleryName));
            if (newFolder != null)
            {
                toReturn = newFolder.FolderID;
            }
            return toReturn;
        }

        public GalleryDNNFileController(int portalId, int moduleId)
        {
            this.PortalId = portalId;
            this.ModuleId = moduleId;
        }


        public int ModuleId { get; set; }
        public int PortalId { get; set; }

        public override ImageEntity GetImage(string imageId)
        {
            ImageEntity toReturn;
           FileInfo currentFile=(FileInfo) DotNetNuke.Services.FileSystem.FileManager.Instance.GetFile(int.Parse(imageId));
         List<ImageEntity> lstImages=  GetImages(currentFile.FolderId.ToString());
           toReturn=(from myImage in  lstImages
                        where myImage.ImageId==imageId
                        select myImage).FirstOrDefault();


            return toReturn;
        }
    }
}